<template>
  <div>
    <el-drawer :title="drawerName" :visible.sync="invoiceDrawervisible" size="70%" style="font-size: 17px">
      <div>
        <div style="width: 100%; height: 60%">
          <el-form :model="invoiceDrawer" ref="invoiceDrawer" label-width="120px" class="form">
            <div style="margin-top: 20px; margin-left: -20px" class="divider-wrapper">
              <el-divider content-position="left">
                <span style="font-weight: bold; color: #077eff">丨</span>
                <span style="margin-left: -2px">购方信息</span>
              </el-divider>
            </div>
            <div style="overflow: hidden">
              <el-link type="primary" :underline="false" style="float: right; right: 25px; font-size: 15px"
                @click="edit">编辑</el-link>
            </div>
            <div style="padding: 0px 0px 0px 25px; font-size: 14px">
              <el-row>
                <el-col :span="8"><span>购方名称：</span>{{ detailData.buyerName }}</el-col>
                <el-col :span="8"><span>购方税号：</span>{{ detailData.buyerTaxNr }}</el-col>
                <el-col :span="8"><span>交付手机：</span>{{ invoiceExt.deliveryPhone }}</el-col>
              </el-row>
              <el-row style="margin: 6px 0px">
                <el-col :span="8"><span>开户行名称：</span>{{ detailData.buyerBankName }}</el-col>
                <el-col :span="8"><span>购方地址：</span>{{ detailData.buyerAddress }} </el-col>
                <el-col :span="8"><span>交付邮箱：</span><span class="spanStyle" :title="invoiceExt.deliveryMail">{{ invoiceExt.deliveryMail }}</span></el-col>
              </el-row>
              <el-row style="margin: 6px 0px">
                <el-col :span="8"><span>开户行账号：</span>{{ detailData.buyerBankAccount }}</el-col>
                <el-col :span="8"><span>购方电话：</span>{{ detailData.buyerTel }}</el-col>
              </el-row>
            </div>

            <div style="margin-top: 20px; margin-left: -20px" class="divider-wrapper">
              <el-divider content-position="left">
                <span style="font-weight: bold; color: #077eff">丨</span>
                <span style="margin-left: -2px">发票信息</span>
              </el-divider>
            </div>
            <div style="padding: 0px 0px 0px 25px; font-size: 14px">
              <el-row>
                <el-col :span="8"><span>订单编号：</span>{{ invoiceExt.documentNr }}</el-col>
                <el-col :span="8"><span>销方名称：</span>{{ detailData.sellerName }}</el-col>
                <el-col :span="8" v-if="detailData.invoiceType == '51'"><span>发票种类：</span>普通发票(电子) </el-col>
                <el-col :span="8" v-if="detailData.invoiceType == '52'"><span>发票种类：</span>专用发票(电子) </el-col>
                <el-col :span="8" v-if="detailData.invoiceType == '2'"><span>发票种类：</span>普通发票(纸质) </el-col>
                <el-col :span="8" v-if="detailData.invoiceType == '0'"><span>发票种类：</span>专用发票(纸质) </el-col>
                <el-col :span="8" v-if="detailData.invoiceType == '61'"><span>发票种类：</span>数电普票</el-col>
                <el-col :span="8" v-if="detailData.invoiceType == '62'"><span>发票种类：</span>数电专票 </el-col>
              </el-row>
              <el-row style="margin: 6px 0px">
                <el-col :span="8" v-if="detailData.positiveType == '1'"><span>发票类型：</span>蓝字发票</el-col>
                <el-col :span="8" v-if="detailData.positiveType == '2'"><span>发票类型：</span>红字发票</el-col>

                <el-col :span="8"><span>部门/门店：</span>-</el-col>
                <el-col :span="6"> <span>税额：</span>{{ detailData.invoiceTax }} </el-col>
              </el-row>
              <el-row style="margin: 6px 0px">
                <el-col :span="8"><span>价税合计：</span>{{ (Number(detailData.invoiceAmount) +
                  Number(detailData.invoiceTax)).toFixed(2) }}</el-col>
                <!-- <el-col :span="8"><span>提交时间：</span>{{ detailData.invoiceExt.createDate }}</el-col> -->
                <el-col :span="6"> <span>收款人：</span>{{ detailData.payee }} </el-col>
              </el-row>
              <el-row style="margin: 6px 0px">
                <el-col :span="8"><span>复核人：</span>{{ detailData.checker }}</el-col>
                <el-col :span="8"><span>开票员：</span>{{ detailData.issuer }}</el-col>
                <el-col :span="6"> <span>备注：</span>{{ detailData.memo }} </el-col>
              </el-row>
              <el-row style="margin: 6px 0px">
                <el-col :span="8"><span>原蓝票代码：</span>{{ detailData.refInvoiceCode }}</el-col>
                <el-col :span="8"><span>原蓝票号码：</span>{{ detailData.refInvoiceNr }}</el-col>
                <el-col :span="6"> <span>冲红原因：</span>- </el-col>
              </el-row>
            </div>
            <div style="margin-top: 20px; margin-left: -20px" class="divider-wrapper">
              <el-divider content-position="left">
                <span style="font-weight: bold; color: #077eff">丨</span>
                <span style="margin: 0px 15px 0px -2px">商品信息</span>
                <el-button type="primary" plain size="mini" @click="addGoods">添加明细</el-button>
              </el-divider>
            </div>
            <el-table :height="250" ref="goodsTable" :data="tableData" highlight-current-row size="small" class="tableSy"
              style="padding: 0px 0px 0px 25px">
              <el-table-column type="index" width="55" label="序号" />
              <el-table-column label="商品名称" key="productName" prop="productName" header-align="center"
                :show-overflow-tooltip="true" align="center" width="200" />
              <el-table-column label="税收分类编码" key="classificationCode" prop="classificationCode" header-align="center"
                align="center" width="200" :show-overflow-tooltip="true" />
              <!-- <el-table-column label="税收分类名称" key="classificationName" prop="classificationName" header-align="center"
                align="center" width="200" :show-overflow-tooltip="true" /> -->
              <el-table-column label="规格型号" key="spec" prop="spec" :show-overflow-tooltip="true" header-align="center"
                align="center" />
              <el-table-column label="单价" key="price" prop="price" header-align="center" align="center"
                :show-overflow-tooltip="true" />

              <el-table-column label="数量" key="num" prop="num" header-align="center" align="center"
                :show-overflow-tooltip="true" />
              <el-table-column label="金额(不含税)" width="90" key="amountExcTax" prop="amountExcTax" header-align="center"
                align="center" :show-overflow-tooltip="true" />
              <el-table-column label="税额" key="tax" prop="tax" header-align="center" align="center"
                :show-overflow-tooltip="true" />

              <el-table-column label="税率" key="taxRate" prop="taxRate" header-align="center" align="center"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  {{ Number(scope.row.taxRate) * 100 + '%' }}
                </template>
              </el-table-column>

              <!-- <el-table-column label="扣除额" key="price" prop="price" header-align="center" align="center" :show-overflow-tooltip="true" /> -->
              <!-- <el-table-column label="折扣金额" key="price" prop="price" header-align="center" align="center" :show-overflow-tooltip="true" /> -->

              <el-table-column label="操作" fixed="right" key="cz" prop="cz" :show-overflow-tooltip="true"
                header-align="center" align="center">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.rowProperty == '2' || scope.row.rowProperty == '0'"
                    @click="editGoods(scope.row, scope.$index)" type="text" size="small">编辑</el-button>
                  <el-popconfirm v-if="tableData.length > 1" title="确认删除?" icon="el-icon-info" placement="left"
                    confirm-button-text="确认" @confirm="delGoods(scope.$index, scope.row)" cancel-button-text="取消">
                    <el-button slot="reference" type="text" size="small">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <div style="position: absolute; right: 3%; bottom: 2%; z-index: 999">
          <el-button size="small" @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitGoodsForm('save')" size="small">保 存</el-button>
          <el-button type="primary" @click="submitGoodsForm('submit')" size="small">提交开票</el-button>
        </div>
        <!-- 购方信息以及发票信息编辑 -->
        <el-drawer title="编辑" :append-to-body="true" :close-on-click-modal="false" :wrapperClosable="false"
          :visible.sync="editDrawer" size="60%" style="font-size: 17px">
          <div style="width: 100%; height: 60%; padding: 55px 0px 0px 15px">
            <el-form :model="invoiceForm" ref="invoiceForm" label-width="120px" :rules="invRules">
              <p>购方信息</p>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="购方名称:" prop="buyerName" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.buyerName" size="small" autocomplete="off"
                      :show-overflow-tooltip="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="购方税号:" prop="buyerTaxNr" clearable>
                    <el-input v-model="invoiceForm.buyerTaxNr" size="small" autocomplete="off"
                      style="width: 250px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="11">
                  <el-form-item label="地址:" prop="buyerAddress" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.buyerAddress" size="small"
                      autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="电话:" prop="buyerTel" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.buyerTel" size="small"
                      autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="开户行:" prop="buyerBankName" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.buyerBankName" size="small"
                      autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="账号:" prop="buyerBankAccount" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.buyerBankAccount" size="small"
                      autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="11">
                  <el-form-item label="交付手机:" prop="deliveryPhone" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.deliveryPhone" size="small"
                      autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="交付邮箱:" prop="deliveryMail" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.deliveryMail" size="small"
                      autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <p>发票信息</p>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="发票种类:" prop="invoiceType" clearable>
                    <el-select style="width: 250px" size="small" v-model="invoiceForm.invoiceType" placeholder="请选择">
                      <el-option v-for="item in invoiceTypeOptions" :key="item.value" :label="item.label"
                        :value="item.value"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="备注:" prop="memo" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.memo" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 红票需要判断 -->
              <!-- <el-row>
                <el-col :span="11">
                  <el-form-item label="原蓝票代码:" prop="amount" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.amount" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="原蓝票号码:" prop="amount" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.amount" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="冲红原因:" prop="amount" clearable>
                    <el-input style="width: 250px" v-model="invoiceForm.amount" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row> -->
            </el-form>
          </div>
          <div style="position: absolute; right: 3%; bottom: 2%">
            <el-button size="small" @click="cancelbuyerInfo">取 消</el-button>
            <el-button type="primary" @click="savebuyerInfo()" size="small">保存</el-button>
          </div>
        </el-drawer>
        <!-- 明细编辑 -->
        <el-drawer title="明细编辑" :append-to-body="true" :wrapperClosable="false" :close-on-click-modal="false"
          :visible.sync="innerProductDrawer" size="60%" style="font-size: 17px">
          <div style="width: 100%; height: 60%; padding: 55px 0px 0px 15px">
            <el-form :model="goodsForm" ref="goodsForm" label-width="120px" :rules="invoiceRules">
              <el-row>
                <el-col :span="11">
                  <el-form-item label="商品名称:" prop="productName" clearable>
                    <el-input style="width: 250px" v-model="goodsForm.productName" size="small" autocomplete="off"
                      :show-overflow-tooltip="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="是否含税:" prop="ishanshui">
                    <el-input style="width: 250px" v-model="goodsForm.ishanshui" size="small" autocomplete="off"
                      :show-overflow-tooltip="true" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="税收分类编码:" prop="classificationCode" clearable class="costFormItem">
                    <div @click="classificationCodeFn">
                      <el-input style="width: 250px" size="small" readonly placeholder="请选择税收分类编码"
                        suffix-icon="el-icon-date" v-model="goodsForm.classificationCode" class="costFormInput"
                        autocomplete="off">
                      </el-input>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="规格型号:" prop="spec" clearable>
                    <el-input v-model="goodsForm.spec" size="small" autocomplete="off" style="width: 250px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="11">
                  <el-form-item label="税收分类简称:" prop="classificationAbbr" clearable>
                    <el-input style="width: 250px" readonly v-model="goodsForm.classificationAbbr" size="small"
                      autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="单位:" prop="unit" clearable>
                    <el-input style="width: 250px" v-model="goodsForm.unit" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="税率:" prop="taxRate" clearable>
                    <el-select v-model="goodsForm.taxRate" size="small" style="width: 250px"
                      @blur="afterEdit(goodsForm.taxRate, 'taxRate')" @change="changeTax">
                      <el-option v-for="item in taxRateOptions" :key="item.value" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="享受优惠政策:" prop="taxPre" clearable class="costFormItem">
                    <el-select v-model="goodsForm.taxPre" :disabled="taxPreDis" class="costFormInput" @change="taxPreChange" size="mini"
                      style="width: 250px">
                      <el-option label="是" value="1"></el-option>
                      <el-option label="否" value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="11">
                  <el-form-item label="零税率标识:" prop="zeroTax" clearable class="costFormItem">
                    <el-select v-model="goodsForm.zeroTax"  style="width: 250px" size="mini" @change="zeroTaxChange()" :disabled="zeroTaxDis"
                      class="costFormInput">
                      <el-option label="否" value=""></el-option>
                      <el-option label="是" value="3"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="11">
                  <el-form-item label="优惠政策类型:" prop="taxPreContent" clearable class="costFormItem">
                    <el-select size="mini" v-model="goodsForm.taxPreContent" :disabled="goodsForm.taxPre == '0'"
                      class="costFormInput" style="width: 250px">
                      <!-- <el-option label="请选择" value=""></el-option> -->
                      <el-option label="免税" value="03"></el-option>
                      <el-option label="不征税" value="04"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="单价:" prop="price" clearable>
                    <el-input @input="checkNumInput(goodsForm.price, 'price')" @blur="afterEdit(goodsForm.price, 'price')"
                      @keyup.enter.native="afterEdit(goodsForm.price, 'price')" style="width: 250px"
                      v-model="goodsForm.price" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="金额:" prop="amountExcTax" clearable>
                    <el-input @input="checkNumInput(goodsForm.amountExcTax, 'amountExcTax')"
                      @blur="afterEdit(goodsForm.amountExcTax, 'amountExcTax')"
                      @keyup.enter.native="afterEdit(goodsForm.amountExcTax, 'amountExcTax')" style="width: 250px"
                      v-model="goodsForm.amountExcTax" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="数量:" prop="num" clearable>
                    <el-input @input="checkNumInput(goodsForm.num, 'num')" @blur="afterEdit(goodsForm.num, 'num')"
                      @keyup.enter.native="afterEdit(goodsForm.num, 'num')" style="width: 250px" v-model="goodsForm.num"
                      size="small" autocomplete="off"></el-input>
                  </el-form-item>               
                </el-col>
                <el-col :span="11">
                  <el-form-item label="折扣金额:" prop="str1" clearable>
                    <el-input @input="checkNumInput(goodsForm.str1, 'str1')" @blur="afterEdit(goodsForm.str1, 'str1')"
                      @keyup.enter.native="afterEdit(goodsForm.str1, 'str1')" style="width: 250px"
                      :disabled="this.disabledTax" v-model="goodsForm.str1" size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="扣除额:" prop="deductionAmount" clearable>
                    <el-input @input="checkNumInput(goodsForm.deductionAmount, 'deductionAmount')"
                      @blur="afterEdit(goodsForm.deductionAmount, 'deductionAmount')"
                      @keyup.enter.native="afterEdit(goodsForm.deductionAmount, 'deductionAmount')"
                      :disabled="this.disabledAmount" style="width: 250px" v-model="goodsForm.deductionAmount"
                      size="small" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div style="position: absolute; right: 3%; bottom: 2%">
            <el-button size="small" @click="cancelGoodsForm">取 消</el-button>
            <el-button type="primary" @click="saveGoodsForm()" size="small">保存</el-button>
          </div>
          <classificationCode-dialog ref="classificationCodeRef"></classificationCode-dialog>
        </el-drawer>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { batchInvoice } from '@/model/validator.js'
import { batchIssue, updateInvoice, codeDetails, autocalculate } from '@/api/output/batchIssue.js'
import classificationCodeDialog from './classificationCode.vue'
import { saveAndIssueManualInvoiceInfo, saveManualInvoiceInfo } from '@/api/output/issue.js'
import { searchBase } from '@/api/output/configmanage.js'

export default {
  components: {
    'classificationCode-dialog': classificationCodeDialog,
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback();
      } else {
        const reg = /^1[34578]\d{9}$/
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"))
        }
      }
    };
    return {
      invRules: {
        buyerName: [
          { required: true, message: '购方名称不能为空', trigger: ['blur'] }
        ],
        // deliveryMail: [
        //   { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        // ],
        deliveryPhone: [
          { validator: checkPhone, trigger: ['blur', 'change'] }
        ]
      },
      invoiceRules: batchInvoice,
      invoiceDrawervisible: false,
      innerProductDrawer: false,
      editDrawer: false,
      drawerName: '发票详情',
      detailData: {},
      invoiceExt: {},
      invoiceDrawer: {
        productId: '',
        productName: '',
        productNr: '',
        classificationCode: '',
        classificationAbbr: '',
        classificationName: '',
        taxRate: '',
        spec: '',
        price: '',
        priceModify: '0',
        ycbz: '1',
        includeTax: '0',
        unit: '',
        taxPre: '0',
        taxPreContent: '',
      },
      tableData: [],
      goodsForm: {
        zeroTax:'',
        productName: '',
        productNr: '',
        classificationCode: '',
        classificationAbbr: '',
        classificationName: '',
        taxRate: '',
        spec: '',
        price: '',
        priceModify: '0',
        ycbz: '1',
        includeTax: '0',
        unit: '',
        taxPre: '0',
        taxPreContent: '',
        ishanshui: '不含税',
        discountAmount: '',
        taxDiscountAmt: '',
        amountExcTax: '',
        tax: '',
        amount: '',
        num: '',
        str1: "",
        deductionAmount: null
      },
      stagingArray: {},
      invoiceForm: {
        productName: '',
        productNr: '',
        classificationCode: '',
        classificationAbbr: '',
        classificationName: '',
        taxRate: '',
        spec: '',
        price: '',
        priceModify: '0',
        ycbz: '1',
        includeTax: '0',
        unit: '',
        taxPre: '0',
        taxPreContent: '',

        buyerName: '',
        buyerTaxNr: '',
        buyerAddress: '',
        buyerTel: '',
        buyerBankName: '',
        buyerBankAccount: '',
        "deliveryPhone": '',
        "deliveryMail": '',
        invoiceType: [],
        memo: ''
      },
      invoiceTypeOptions: [
        {
          value: '2',
          label: '普通发票(纸质)',
        },
        {
          value: '0',
          label: '专用发票(纸质)',
        },
        {
          value: '51',
          label: '普通发票(电子)',
        },
        {
          value: '52',
          label: '专用发票(电子)',
        },
        {
          value: '61',
          label: '数电普票',
        },
        {
          value: '62',
          label: '数电专票',
        },
      ],

      selection: [],
      disabledTax: false,
      disabledAmount: false,
      zhekou: false,
      zeroTaxDis: false,
      taxPreDis: false,
      rowData: [],
      taxRateOptions: [],
      currentIndex: '',
      flag: '',
      taxList: [],
      taxRateOptionsBf: []
    }
  },
  methods: {
    initData(data, rowData, invoiceId) {
      this.rowData = rowData
      this.detailData = data
      this.invoiceExt = data.invoiceExt
      this.tableData = JSON.parse(JSON.stringify(rowData))
      // 手动赋值折扣金额，暂存至str1
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].rowProperty == '2') {
          this.tableData[i].str1 = Number(this.tableData[i + 1].amountExcTax) * -1
        }
      }
      this.selection[0] = invoiceId
      this.initParm()
    },
    // 关闭查看明细
    cancel() {
      this.disabledTax = false
      this.disabledAmount = false
      this.invoiceDrawervisible = false
    },
    // 提交开票
    submitGoodsForm(flag) {
      let midChar = '差';
      let char='。'
      if (this.goodsForm.deductionAmount == '' || Number(this.goodsForm.deductionAmount) == 0 || this.goodsForm.deductionAmount == undefined) {
        let index = this.detailData.memo.indexOf(midChar)
        if (index != -1) {
          let substring7 = this.detailData.memo.substring( this.detailData.memo.indexOf(char) + 1,this.detailData.memo.length);
          this.detailData.memo = substring7
        }
        this.goodsForm.deductionAmount = null
      } else {
        let index = this.detailData.memo.indexOf(midChar)
        if (index != -1) {
          let substring7 = this.detailData.memo.substring( this.detailData.memo.indexOf(char) + 1,this.detailData.memo.length);
          this.detailData.memo = '差额征税：' + this.goodsForm.deductionAmount + '。'+substring7
        } else {
          this.detailData.memo ='差额征税：' + this.goodsForm.deductionAmount + '。'+ this.detailData.memo 
        }
      }
      let param
      param = this.detailData
      param.items = this.tableData
      param.deductionAmount = this.goodsForm.deductionAmount
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      for(let i=0;i<param.items.length;i++){
        param.items[i].sequence=i+1;
      }
      if (flag == 'save') {
        saveManualInvoiceInfo(param).then((res) => {
          if (res.code == '0') {
            loading.close()
            this.$message({
              message: '发票保存成功！',
              type: 'success',
            })
            this.invoiceDrawervisible = false
            this.$parent.searchFn()
          } else {
            loading.close()
            this.$message({
              message: res.message,
              type: 'error',
            })
          }
        })
      } else if (flag == 'submit') {
        saveAndIssueManualInvoiceInfo(param).then((res) => {
          if (res.code == '0') {
            this.buttonDisabled = true
            loading.close()
            this.$message({
              message: '发票提交成功！',
              type: 'success',
            })
            this.invoiceDrawervisible = false
            this.$parent.searchFn()
          } else {
            loading.close()
            this.$message({
              message: res.message,
              type: 'error',
            })
            if (res.message == '扫脸认证已超时，请重新认证') {
              setTimeout(() => {
                this.$refs.authenticationRef.authenticationVisible = true
                this.$refs.authenticationRef.buildQRCodeMethod()
              }, 300)
            }
          }
        })
      }

    },
    // 上面的编辑
    edit() {
      this.editDrawer = true
      this.invoiceForm.buyerName = this.detailData.buyerName
      this.invoiceForm.buyerTaxNr = this.detailData.buyerTaxNr
      this.invoiceForm.buyerAddress = this.detailData.buyerAddress
      this.invoiceForm.buyerTel = this.detailData.buyerTel
      this.invoiceForm.buyerBankName = this.detailData.buyerBankName
      this.invoiceForm.buyerBankAccount = this.detailData.buyerBankAccount
      this.invoiceForm.invoiceType = this.detailData.invoiceType
      this.invoiceForm.memo = this.detailData.memo
      this.invoiceForm.deliveryMail = this.invoiceExt.deliveryMail
      this.invoiceForm.deliveryPhone = this.invoiceExt.deliveryPhone
    },
    addGoods() {
      if (this.tableData.length == 1) {
        if (this.tableData[0].deductionAmount && Number(this.tableData[0].deductionAmount) != 0) {
          this.$message({
            message: '该条明细含有扣除额，不可添加明细',
            type: 'warning',
          })
          return
        }
      }
      if (this.$refs['goodsForm']) {
        this.$refs['goodsForm'].resetFields()
      }
      this.goodsForm.productName = ''
      this.goodsForm.productId = ''
      this.goodsForm.productNr = ''
      this.goodsForm.classificationCode = ''
      this.goodsForm.classificationAbbr = ''
      this.goodsForm.classificationName = ''
      this.goodsForm.classificationVersion = ''
      this.goodsForm.taxRate = ''
      this.goodsForm.spec = ''
      this.goodsForm.price = ''
      this.goodsForm.amountExcTax = ''
      this.goodsForm.amount = ''
      this.goodsForm.num = ''
      this.goodsForm.priceModify = '1'
      this.goodsForm.ycbz = '1'
      this.goodsForm.includeTax = '0'
      this.goodsForm.unit = ''
      this.goodsForm.taxPre = '0'
      this.goodsForm.taxPreContent = ''
      this.goodsForm.zeroTax = ''
      this.goodsForm.str1 = ''
      this.flag = 'add'
      // 添加明细时，明细条数不为0，不可添加扣除额
      if (this.tableData.length > 0) {
        this.disabledAmount = true
      } else {
        this.disabledAmount = false
      }
      this.initParm()
      this.innerProductDrawer = true
    },
    // 打开单条明细编辑（下面的编辑）
    editGoods(data, index) {
      this.zhekou = false
      this.currentIndex = index
      // 手动删除折扣行以后，再进行编辑
      if (data.rowProperty == '0') {
        data.str1 = ''
      }

      let goodsData= JSON.parse(JSON.stringify(data))
      this.goodsForm.productName=goodsData.productName
      this.goodsForm.productNr=goodsData.productNr

      this.goodsForm.classificationCode=goodsData.classificationCode
      this.goodsForm.classificationAbbr=goodsData.classificationAbbr
      this.goodsForm.classificationName=goodsData.classificationName
      this.goodsForm.spec=goodsData.spec
      this.goodsForm.includeTax=goodsData.includeTax
      this.goodsForm.taxRate=goodsData.taxRate
      this.goodsForm.price=goodsData.price
      this.goodsForm.priceModify=goodsData.priceModify
      this.goodsForm.ycbz=goodsData.ycbz
      this.goodsForm.unit=goodsData.unit
      this.goodsForm.taxPre=goodsData.taxPre
      this.goodsForm.zeroTax=goodsData.zeroTax
      this.goodsForm.taxPreContent=goodsData.taxPreContent
      this.goodsForm.taxDiscountAmt=goodsData.taxDiscountAmt
      this.goodsForm.amountExcTax=goodsData.amountExcTax
      this.goodsForm.tax=goodsData.tax
      this.goodsForm.amount=goodsData.amount
      this.goodsForm.num=goodsData.num
      this.goodsForm.deductionAmount=JSON.parse(JSON.stringify(this.detailData.deductionAmount))    
      // 分离税收分类简称 商品名
      let Abbr = this.goodsForm.productName.match(/\*(\S*)\*/)[1];
      let indexStr = this.goodsForm.productName.indexOf("*", index + 1)
      let result = this.goodsForm.productName.substring(indexStr + 1)
      this.goodsForm.productName = result
      this.goodsForm.classificationAbbr = Abbr

      this.goodsForm['kouchue'] = this.detailData.deductionAmount
      // 明细默认不含税
      this.goodsForm.ishanshui = '不含税'
      if (data.rowProperty == '2') {
        this.$message({
          showClose: true,
          message: '被折扣行不可编辑，请先删除折扣行',
          type: 'warning',
        })
        return
      }
      // 折扣金额有值时，扣除额不可编辑
      if (this.goodsForm.str1 != '' && this.goodsForm.str1 != 0 && this.goodsForm.str1 != undefined) {
        this.disabledAmount = true
      } else {
        this.disabledAmount = false
      }
      // 明细只有一条时才可编辑扣除额
      if (this.tableData.length > 1) {
        this.disabledAmount = true
      } else {
        this.disabledAmount = false
      }
      // 扣除额有值时，折扣金额不可编辑
      if (this.goodsForm.deductionAmount != '' && this.goodsForm.deductionAmount != 0 && this.goodsForm.deductionAmount != undefined) {
        this.disabledTax = true
      } else {
        this.disabledTax = false
      }
      // 数电票不可编辑差额
      if(this.detailData.invoiceType=='61'||this.detailData.invoiceType=='62'){
        this.disabledAmount=true
      }else{
        this.disabledAmount=false
      }

      let param = {
        classificationCode: this.goodsForm.classificationCode,
      }
      this.innerProductDrawer = true
      this.flag = 'edit'
      if (this.goodsForm.zeroTax != "3") {
        this.goodsForm.zeroTax = ""
        if (this.goodsForm.taxPre != "1") {
          this.taxPreContentDis = true
          this.zeroTaxDis = false
          this.initParm()
        } else {
          this.taxRateOptions = []
          var taxParm = {
            "value": "0",
            "label": "0%",
          }
          this.taxRateOptions.push(taxParm)
          this.taxPreContentDis = false
          this.zeroTaxDis = true
        }
      } else {
        this.taxRateOptions = []
        var taxParm = {
          "value": "0",
          "label": "0%",
        }
        this.taxRateOptions.push(taxParm)
        this.taxPreDis = true
        this.zeroTaxDis = false
      }
    },

    delGoods(index, row) {
      if (this.tableData.length == 2 && this.tableData[index].rowProperty == '2') {
        this.$message({
          showClose: true,
          message: '不可删除，请最少保留一条明细',
          type: 'warning',
        })
        return
      }
      if (row.rowProperty == '1') {
        this.tableData.splice(Number(index), 1)
        this.tableData[Number(index) - Number(1)].rowProperty = '0'
        this.goodsForm.str1=''
      } else if (row.rowProperty == '2') {           
        this.tableData.splice(Number(index), 2)       
      } else {
        this.tableData.splice(Number(index), 1)
      }
    },
    // 字符校验
    checkNumInput(val, prop) { },
    //编辑完毕
    afterEdit(val, prop) {
      if (prop == 'price') {
        this.autocalculatebackstage('numChange')
      }
      if (prop == 'num') {
        this.autocalculatebackstage('numChange')
      }
      if (prop == 'amountExcTax') {
        this.autocalculatebackstage('amountExcTaxChange')
      }
      // 扣除额
      if (prop == 'deductionAmount') {
        if (val != 0 && val != '' && val != null && val != undefined) {
          this.disabledTax = true
        } else {
          this.disabledTax = false
        }
        this.autocalculatebackstage('deductionChange')
      }
      // 折扣
      if (prop == 'str1') {
        if (val != 0 && val != '' && val != null && val != undefined) {
          this.zhekou = true
        } else {
          this.zhekou = false
        }
        if ((val != 0 && val != '' && val != null && val != undefined) || this.tableData.length > 1) {
          this.disabledAmount = true
        } else {
          this.disabledAmount = false
        }
        this.autocalculatebackstage('discountAmtChange')
      }
    },
    changeTax(val){
      // 税率         
      this.autocalculatebackstage('amountExcTaxChange')    
    },

    //数据的联动计算
    async autocalculatebackstage(method) {
      let param
      param = this.goodsForm
      // 扣除额
      param['deductionAmount'] = this.goodsForm.deductionAmount
      // 折扣金额
      param['discountAmount'] = this.goodsForm.str1
      param.method = method
      param['includeTax'] = '0'
      param['invIncludeTax'] = '0'
      let res = await autocalculate(param)
      if (res.code === 0) {
        let resRow = res.data
        if (method != 'discountAmtChange') {
          this.goodsForm.amountExcTax = resRow.amountExcTax
          this.goodsForm.price = resRow.price
          this.goodsForm.num = resRow.num
          this.goodsForm.tax = resRow.tax
          this.goodsForm.taxRate = resRow.taxRate
          this.goodsForm.amount = resRow.amount
        } else {
          this.stagingArray = JSON.parse(JSON.stringify(this.goodsForm))
          this.stagingArray.amountExcTax = resRow.amountExcTax
          this.stagingArray.price = resRow.price
          this.stagingArray.num = resRow.num
          this.stagingArray.tax = resRow.tax
          this.stagingArray.taxRate = resRow.taxRate
          this.stagingArray.amount = resRow.amount
        }

      }
    },
    // 取消购方信息以及发票信息
    cancelbuyerInfo() {
      this.$refs['invoiceForm'].resetFields()
      this.editDrawer = false
    },
    // 保存购方信息以及发票信息
    savebuyerInfo() {
      this.$refs['invoiceForm'].validate((valid) => {
        if (!valid) {
          this.$message({
            message: '请修改正确的数据格式！',
            type: 'error',
          })
          return

        } else {
          this.detailData.buyerName = this.invoiceForm.buyerName
          this.detailData.buyerTaxNr = this.invoiceForm.buyerTaxNr
          this.detailData.buyerAddress = this.invoiceForm.buyerAddress
          this.detailData.buyerTel = this.invoiceForm.buyerTel
          this.detailData.buyerBankName = this.invoiceForm.buyerBankName
          this.detailData.buyerBankAccount = this.invoiceForm.buyerBankAccount
          this.detailData.invoiceType = this.invoiceForm.invoiceType
          this.detailData.memo = this.invoiceForm.memo
          this.detailData.invoiceExt.deliveryMail = this.invoiceForm.deliveryMail
          this.detailData.invoiceExt.deliveryPhone = this.invoiceForm.deliveryPhone

          this.invoiceExt.deliveryMail = this.invoiceForm.deliveryMail
          this.invoiceExt.deliveryPhone = this.invoiceForm.deliveryPhone
          this.editDrawer = false
        }
      })
    },
    classificationCodeFn() {
      this.$refs.classificationCodeRef.dialog = true
    },
    // 取消商品明细编辑
    cancelGoodsForm() {
      // 还原折扣数据
      for (let i = 0; i < this.rowData.length; i++) {
        if (this.rowData[i].rowProperty == '2') {
          this.tableData[i].str1 = Number(this.rowData[i + 1].amountExcTax) * -1
        }
      }
      // 还原扣除额
      this.goodsForm.deductionAmount = this.goodsForm.kouchue
      this.$refs['goodsForm'].resetFields()
      this.disabledTax = false
      this.disabledAmount = false
      this.innerProductDrawer = false
    },
    // 商品明细编辑
    saveGoodsForm() {
      if (Number(this.goodsForm.str1) > Number(this.goodsForm.amountExcTax)) {
        this.$message({
          showClose: true,
          message: '折扣金额不能大于商品金额！',
          type: 'warning',
        })
        return
      }
      // 在有明细的情况下，新增一条明细，扣除额不可编辑
      if (this.flag == 'add') {
        if (this.tableData.length > 0) {
          this.disabledAmount = true
        } else {
          this.disabledAmount = false
        }
      } 
      // else if (this.flag == 'edit') {
      //   // 保存明细时，扣除额不为空，明细按钮隐藏
      //   if (this.goodsForm.deductionAmount && Number(this.goodsForm.deductionAmount) != 0) {
      //     this.disabledAmount = true
      //   } else {
      //     this.disabledAmount = false
      //   }
      // }

      let element = this.goodsForm.taxRate
      let index = this.taxList.indexOf(element)
      if (index == -1) {
        this.$message({
          showClose: true,
          message: '该税率不在企业可选税率范围内！',
          type: 'warning',
        })
        return
      }
      this.$refs['goodsForm'].validate((valid) => {
        if (!valid) {
          this.$message({
            message: '请修改正确的数据格式！',
            type: 'error',
          })
          return
        } else {
          if (this.flag == 'add') {
            // 新增清空下，折扣不为空
            if (this.goodsForm.str1 && Number(this.goodsForm.str1) != 0) {
              let data = JSON.parse(JSON.stringify(this.goodsForm))
              data.productName = '*' + JSON.parse(JSON.stringify(this.goodsForm.classificationAbbr)) + '*' + JSON.parse(JSON.stringify(this.goodsForm.productName))
              data.rowProperty = '0'
              this.tableData.push(data)
              let row = {
                productName: null,
                spec: null,
                unit: null,
                num: null,
                price: null,
                taxRate: null,
                tax: null,
                amount: null,
                amountExcTax: null,
                classificationVersion: null,
                classificationCode: null,
              }
              row = JSON.parse(JSON.stringify(this.stagingArray))
              row.rowProperty = '1'
              row.unit = ''
              row.spec = ''
              row.num = ''
              row.price = ''
              row.productName = '*' + JSON.parse(JSON.stringify(this.goodsForm.classificationAbbr)) + '*' + JSON.parse(JSON.stringify(this.goodsForm.productName))
              this.tableData.splice(this.tableData.length, 0, row)
              this.tableData[this.tableData.length - 2].rowProperty = '2'
            } else {
              let data = JSON.parse(JSON.stringify(this.goodsForm))
              data.productName = '*' + JSON.parse(JSON.stringify(this.goodsForm.classificationAbbr)) + '*' + JSON.parse(JSON.stringify(this.goodsForm.productName))
              data.rowProperty = '0'
              this.tableData.push(data)
            }
          } else if (this.flag == 'edit') {
            // 如果添加折扣金额
            if (this.goodsForm.str1 && Number(this.goodsForm.str1) != 0) {
              let row = {
                productName: null,
                spec: null,
                unit: null,
                num: null,
                price: null,
                taxRate: null,
                tax: null,
                amount: null,
                amountExcTax: null,
                classificationVersion: null,
                classificationCode: null,
              }
              row = JSON.parse(JSON.stringify(this.stagingArray))
              row.rowProperty = '1'
              row.unit = ''
              row.spec = ''
              row.num = ''
              row.price = ''
              row.productName = '*' + this.stagingArray.classificationAbbr + '*' + this.stagingArray.productName
              this.tableData.splice(Number(this.currentIndex) + 1, 0, row)
              this.tableData[this.currentIndex].rowProperty = '2'
              this.saveDetail()
            } else {
              this.saveDetail()
            }
          }
          this.innerProductDrawer = false
        }
      })
    },
    saveDetail() {
      this.tableData[this.currentIndex].classificationCode = this.goodsForm.classificationCode
      this.tableData[this.currentIndex].spec = this.goodsForm.spec
      this.tableData[this.currentIndex].unit = this.goodsForm.unit
      this.tableData[this.currentIndex].taxRate = this.goodsForm.taxRate
      this.tableData[this.currentIndex].tax = this.goodsForm.tax
      this.tableData[this.currentIndex].price = this.goodsForm.price
      this.tableData[this.currentIndex].num = this.goodsForm.num
      this.tableData[this.currentIndex].amountExcTax = this.goodsForm.amountExcTax
      this.tableData[this.currentIndex].taxPre = this.goodsForm.taxPre
      this.tableData[this.currentIndex].taxPreContent = this.goodsForm.taxPreContent
      this.tableData[this.currentIndex].zeroTax = this.goodsForm.zeroTax
      //  折扣金额未赋值
      this.tableData[this.currentIndex].deductionAmount = this.goodsForm.deductionAmount
      this.detailData.deductionAmount = this.goodsForm.deductionAmount
      this.tableData[this.currentIndex].productName = '*' + this.goodsForm.classificationAbbr + '*' + this.goodsForm.productName
    },
    zeroTaxChange() {
      if (this.goodsForm.zeroTax == "3") {
        this.taxRateOptions = []
        var taxParm = {
          "value": "0",
          "label": "0%",
        }
        this.taxRateOptions.push(taxParm)
        this.goodsForm.taxPre = "0"
        this.goodsForm.taxRate = "0"
        this.goodsForm.taxPreContent = ""
        this.taxPreDis = true
      } else {
        this.taxRateOptions = this.taxRateOptionsBf
        this.goodsForm.taxPre = "0"
        this.goodsForm.taxRate = this.taxRateOptions[0].value
        this.goodsForm.taxPreContent = ""
        this.taxPreDis = false
      }
    },

    taxPreChange() {
      if (this.goodsForm.taxPre == '1') {
        this.taxRateOptions = []
        var taxParm = {
          value: '0',
          label: '0%',
        }
        this.taxRateOptions.push(taxParm)
        this.goodsForm.taxRate = '0'
        this.goodsForm.taxPreContent = '03'
        this.goodsForm.zeroTax = ''
        this.autocalculatebackstage('amountExcTaxChange')
        this.zeroTaxDis=true
      } else {
        this.taxRateOptions = this.taxRateOptionsBf
        this.goodsForm.taxPreContent = ''
        this.goodsForm.taxRate = this.taxRateOptions[0].value
        this.goodsForm.zeroTax = ''
        this.zeroTaxDis=false
      }
    },
    //查询基础配置税率
    initParm() {
      searchBase('1').then((res) => {
        if (res.code == 0) {
          var jsonParm = JSON.parse(res.data.taxRateConfig.taxRateList)
          this.taxRateOptions = []
          const map = new Map()
          for (var i = 0; i < jsonParm.length; i++) {
            var parm = JSON.parse(jsonParm[i]) * 100 + '%'
            var taxParm = {
              value: jsonParm[i],
              label: parm,
            }
            this.taxRateOptions.push(taxParm)
          }
          this.taxRateOptionsBf = this.taxRateOptions
          this.taxList = res.data.taxRateConfig.taxRateArray
        }
      })
    },
  },
}
</script>
<style>
.form {
  overflow: hidden;
}

.divider-wrapper /deep/.el-drawer {
  width: 92% !important;
}

.el-drawer__header {
  margin-bottom: 0px !important;
}

.spanStyle {
  display: inline-block;
  white-space: normal;
  width: 200px;
  overflow: hidden; /*超出的文本隐藏*/
  text-overflow: ellipsis; /* 溢出用省略号*/
  line-height: 15px;
}
</style>